package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HELP_INFORMATION;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.IMTOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USERID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USER_NAME;
import static com.netease.yunxin.kit.conversationkit.ui.view.ConversationAdapter.imOfficialBean;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luoxiang.lib_common.common.Constants;
import com.luoxiang.lib_common.utils.NetUtils;
import com.luoxiang.socialandroid.BuildConfig;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.NavigationAdapter;
import com.luoxiang.socialandroid.app.MyAppliaction;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.base.SelfNERtcCallExtension;
import com.luoxiang.socialandroid.bean.GreetBean;
import com.luoxiang.socialandroid.bean.HelpInformation;
import com.luoxiang.socialandroid.bean.MineInfoBean;
import com.luoxiang.socialandroid.bean.NewVersionBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.UserBeautyBean;
import com.luoxiang.socialandroid.dialog.BatchGreetingDialog;
import com.luoxiang.socialandroid.dialog.NewVersionDialog;
import com.luoxiang.socialandroid.dialog.OneTouchChatDialog;
import com.luoxiang.socialandroid.dialog.SuspendedWindowDialog;
import com.luoxiang.socialandroid.dialog.UserBehaviorTipDialog;
import com.luoxiang.socialandroid.event.HangUpEvent;
import com.luoxiang.socialandroid.face.data.disksource.FUUtils;
import com.luoxiang.socialandroid.face.data.disksource.FaceBeautyData;
import com.luoxiang.socialandroid.face.view.FaceBeautyActivity;
import com.luoxiang.socialandroid.fragment.CommunityFragment;
import com.luoxiang.socialandroid.fragment.HomeFragment;
import com.luoxiang.socialandroid.fragment.ListFragment;
import com.luoxiang.socialandroid.fragment.MineFragment;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.DelayUtil;
import com.luoxiang.socialandroid.utils.LoginUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.luoxiang.socialandroid.viewpager.CustomViewPager;
import com.lxj.xpopup.XPopup;
import com.netease.lava.nertc.sdk.NERtcConstants;
import com.netease.lava.nertc.sdk.NERtcOption;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nis.quicklogin.QuickLogin;
import com.netease.yunxin.kit.chatkit.ui.ChatKitClient;
import com.netease.yunxin.kit.chatkit.ui.ChatUIConfig;
import com.netease.yunxin.kit.chatkit.ui.view.message.MessageProperties;
import com.netease.yunxin.kit.conversationkit.ui.ConversationKitClient;
import com.netease.yunxin.kit.conversationkit.ui.ConversationUIConfig;
import com.netease.yunxin.kit.conversationkit.ui.ItemClickListener;
import com.netease.yunxin.kit.conversationkit.ui.model.ConversationBean;
import com.netease.yunxin.kit.conversationkit.ui.page.ConversationFragment;
import com.netease.yunxin.kit.corekit.im.IMKitClient;
import com.netease.yunxin.kit.corekit.im.login.LoginCallback;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.nertc.ui.CallKitNotificationConfig;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.CallKitUIOptions;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;

/**
 * 首页的activtiy
 */
public class HomeActivity extends BaseActivity {
    private List<Fragment> mFragments;
    private ViewPager2 vpMain;
    private RadioGroup rgMain;
    private RadioButton rb_home;
    private ImageView ic_right;
    private TextView textNoReading;
    public static HomeActivity instance;
    private Long nowTime = 0L;
    private static Boolean isQuit = false;

    Timer timer = new Timer();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isQuit == false) {
                isQuit = true;
                ToastUtils.showShort(R.string.mi_app_exit_tip);
                TimerTask task = null;

                task = new TimerTask() {
                    @Override
                    public void run() {
                        isQuit = false;
                    }
                };

                timer.schedule(task, 2000);
            } else {
                EventBus.getDefault().post(new HangUpEvent());

                finishAll();
                QuickLogin.getInstance().quitActivity();
                System.exit(0);
            }
        }
        return false;

    }

    //判断是否开启悬浮窗权限   context可以用你的Activity.或者tiis
    public static boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
                        .getPackageName());
                return mode == AppOpsManager.MODE_ALLOWED;
            } else {
                return Settings.canDrawOverlays(context);
            }
        }
    }


    private void getNewversion(String token, String extra, String type) {
        getRequest();
        NetUtils.getInstance().getApiService().getNewestVersion(token, extra, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<com.luoxiang.lib_common.bean.NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(com.luoxiang.lib_common.bean.NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr800", decryptStr);
                        Gson gson = new Gson();
                        NewVersionBean newVersionBean = gson.fromJson(decryptStr, NewVersionBean.class);
                        if (newVersionBean == null) return;
                        if (newVersionBean.getData() != null) {
                            if (newVersionBean.getData().getVersion() == null) return;
                            NewVersionDialog dialog = new NewVersionDialog(HomeActivity.this);
                            if (newVersionBean.getData().getVersion().getCode() > BuildConfig.VERSION_CODE) {
                                // 强制更新
                                if (newVersionBean.getData().getVersion().getMust() == 1) {
                                    dialog.setOnConfirmClickListener(new Function0<Unit>() {
                                        @Override
                                        public Unit invoke() {
                                            //点击确定
                                            AllenVersionChecker
                                                    .getInstance()
                                                    .downloadOnly(
                                                            UIData.create().setDownloadUrl(newVersionBean.getData().getVersion().getUrl())
                                                                    .setTitle("当前有新版本" + newVersionBean.getData().getVersion().getVersion())
                                                                    .setContent(newVersionBean.getData().getVersion().getContent())
                                                    )
                                                    .setForceUpdateListener(() -> {
                                                        AppUtils.exitApp();
                                                    })
                                                    .executeMission(HomeActivity.this);
                                            dialog.dismiss();
                                            return null;
                                        }
                                    });
                                    dialog.setOnCancleClickListener(new Function0<Unit>() {
                                        @Override
                                        public Unit invoke() {
                                            finishAll();
                                            QuickLogin.getInstance().quitActivity();
                                            System.exit(0);
                                            return null;
                                        }
                                    });
                                    dialog.setTitle(newVersionBean.getData().getVersion().getVersion() + getString(R.string.mi_banbengengxintongzhi));//设置title
                                    dialog.setContent(newVersionBean.getData().getVersion().getContent());//设置文本
                                    new XPopup.Builder(HomeActivity.this)
                                            .dismissOnBackPressed(false)
                                            .asCustom(dialog)
                                            .show();
                                } else {
                                    // 非强制更新
                                    dialog.setOnConfirmClickListener(new Function0<Unit>() {
                                        @Override
                                        public Unit invoke() {
                                            //点击确定
                                            AllenVersionChecker
                                                    .getInstance()
                                                    .downloadOnly(
                                                            UIData.create().setDownloadUrl(newVersionBean.getData().getVersion().getUrl())
                                                                    .setTitle("当前有新版本" + newVersionBean.getData().getVersion().getVersion())
                                                                    .setContent(newVersionBean.getData().getVersion().getContent())
                                                    )
                                                    .executeMission(HomeActivity.this);
                                            dialog.dismiss();
                                            return null;
                                        }
                                    });
                                    dialog.setTitle(newVersionBean.getData().getVersion().getVersion() + getString(R.string.mi_banbengengxintongzhi));//设置title
                                    dialog.setContent(newVersionBean.getData().getVersion().getContent());//设置文本
                                    new XPopup.Builder(HomeActivity.this)
                                            .asCustom(dialog)
                                            .show();
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void initListener() {
        LiveEventBus.get("startOfficialIm").observe(this, o ->
                startActivity(new Intent(this, OfficialImActivity.class)));
        LiveEventBus.get("tokenFailure").observe(this, o ->
                {
                    MmkvUtil.INSTANCE.encode(TOKEN, "");
                    MmkvUtil.INSTANCE.encode(ACCID, "");
                    MmkvUtil.INSTANCE.encode(IMTOKEN, "");
                    MmkvUtil.INSTANCE.encode(HOSTAUDIT, "");
                    MmkvUtil.INSTANCE.encode(USER_NAME, "");
                    MmkvUtil.INSTANCE.encode("phone", "");
                    MmkvUtil.INSTANCE.encode(USERID, "");
                    MmkvUtil.INSTANCE.encode("datingModeId", "");
                    MmkvUtil.INSTANCE.encode("emotioRelationId", "");
                    MmkvUtil.INSTANCE.encode("targetAgeId", "");
                    MmkvUtil.INSTANCE.encode("sexpait", "");
                    MmkvUtil.INSTANCE.encode("ed_rename", "");
                    MmkvUtil.INSTANCE.encode("isshowdialogbatch", "");
                    MmkvUtil.INSTANCE.encode("usericon", "");
                    LoginUtil.Companion.initLogin(
                            HomeActivity.this,
                            result -> {
                                LoginUtil.Companion.startLogin(HomeActivity.this, result);
                                ToastUtils.showShort(getString(R.string.mi_dangqianzhanghaoyibeidenglu));
                                finish();
                                return null;
                            },
                            () -> {
                                return null;
                            },
                            () -> {
                                clearLoading();
                                return null;
                            });
                }
        );
        LiveEventBus.<String>get("startDetailsActivity").observe(this, userId -> {
            Intent intent = new Intent(HomeActivity.this, DetailsActivity.class);
            intent.putExtra("userid", Integer.valueOf(userId));
            startActivity(intent);
        });
        LiveEventBus.<Integer>get("startReportActivity").observeForever(userid -> {
            Intent intent = new Intent(HomeActivity.this, ReportActivity.class);
            intent.putExtra("userId", userid);
            startActivity(intent);
        });
        LiveEventBus.get("startWalletActivity").observe(this, o -> {
            Intent intent = new Intent(HomeActivity.this, WalletActivity.class);
            startActivity(intent);
        });
        LiveEventBus.get("RefreshNoReading").observe(this, o -> {
            int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
            int imOfficialNum = 0;
            if (imOfficialBean != null) {
                imOfficialNum = imOfficialBean.getData().getOfficialMsgInfo().getNewestMsg().getNotRead();
            }
            unreadNum += imOfficialNum;
            if (unreadNum == 0) {
                textNoReading.setVisibility(View.GONE);
            } else {
                textNoReading.setVisibility(View.VISIBLE);
                if (unreadNum > 99) {
                    textNoReading.setText("99+");
                } else {
                    textNoReading.setText(String.valueOf(unreadNum));
                }
            }
        });
    }
//
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//            Long time = System.currentTimeMillis();
//            nowTime += 3 * 1000;
//            if (nowTime < time) {
//                //todo 退出app
//                System.exit(0);
//            } else {
//                ToastUtils.showShort("再按一次返回键退出应用");
//            }
//            return false;
//
//        } else {
//            return super.onKeyDown(keyCode, event);
//        }
//
//
//    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_home);
        UltimateBarX.statusBarOnly(this).transparent().light(true).apply();
//        getNewversion(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA, "0");
    }

    @Override
    protected void initView() {
        vpMain = findViewById(R.id.vp_main);
        rgMain = findViewById(R.id.rg_main);
        rb_home = findViewById(R.id.rb_home);
        textNoReading = findViewById(R.id.textNoReading);

        initViewByRG();
        rb_home.setChecked(true);
        String imtoken = MmkvUtil.INSTANCE.decodeString(Constants.MmkvConst.IMTOKEN);
        Integer accid = MmkvUtil.INSTANCE.decodeInt(ACCID);
        String account = String.valueOf(accid);
        doLogin(account, imtoken);
        instance = this;
        initUIConfig();
//        initScreenRecorderBuild();
        getGift(MmkvUtil.INSTANCE.decodeString(TOKEN));
        LiveEventBus.get("refreshData").observe(this, o -> {
            getGift(MmkvUtil.INSTANCE.decodeString(TOKEN));
        });
        getHelpInformation();
        getHostCallContents(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA);
        showUserBehaviorTipDialog();
        com.luoxiang.socialandroid.utils.NetUtils.getInstance().getApiService().getUserBeautyConfig(MmkvUtil.INSTANCE.decodeString(TOKEN), 0)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        UserBeautyBean userBeautyBean = gson.fromJson(decryptStr, UserBeautyBean.class);
                        if (userBeautyBean == null || userBeautyBean.getData() == null || userBeautyBean.getData().getData() == null) {
                            return;
                        }
                        FaceBeautyActivity.userBeautyConfigBean = userBeautyBean.getData().getData();
                        FaceBeautyData faceBeautyData = gson.fromJson(FaceBeautyActivity.userBeautyConfigBean.getBeautyConfig(), FaceBeautyData.class);
                        if (faceBeautyData == null) {
                            return;
                        }


                        FUUtils.saveFaceBeautyData2File(faceBeautyData);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
        String isshowdialogbatch = MmkvUtil.INSTANCE.decodeString("isshowdialogbatch");
        if (isshowdialogbatch.equals("showdialog") && MmkvUtil.INSTANCE.decodeInt(HOSTAUDIT) != 1) {
            BatchGreetingDialog dialogbatch = new BatchGreetingDialog(HomeActivity.this);
            getRequest();
            dialogbatch.setOnCancleClickListener(new Function0<Unit>() {
                @Override
                public Unit invoke() {
                    dialogbatch.dismiss();
                    return null;
                }
            });
            dialogbatch.setOnTrueClickListener(() -> {
                dialogbatch.dismiss();
                return null;
            });
            new XPopup.Builder(HomeActivity.this)
                    .asCustom(dialogbatch)
                    .show();
        }
        getHomeUserInfo(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA);
        new DelayUtil(this).delayJob(5 * 1000, () -> {
            boolean result = checkFloatPermission(HomeActivity.this);
            if (!result) {
                new XPopup.Builder(HomeActivity.this)
                        .asCustom(new SuspendedWindowDialog(HomeActivity.this))
                        .show();
            }
            return null;
        });
    }

    //弹出用户行为须知
    private void showUserBehaviorTipDialog() {
        Boolean isShowUserBehaviorTip = MmkvUtil.INSTANCE.decodeBoolean("isShowUserBehaviorTip");
        if (isShowUserBehaviorTip == null || !isShowUserBehaviorTip) {
            MmkvUtil.INSTANCE.encode("isShowUserBehaviorTip", true);
            new XPopup.Builder(HomeActivity.this)
                    .asCustom(new UserBehaviorTipDialog(this))
                    .show();
        }
    }

    private void getHostCallContents(String token, String extra) {
        NetUtils2.getInstance().getApiService().getHostCallContents(token, extra, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStr00", decryptStr);
                            Gson gson = new Gson();
                            GreetBean bean = gson.fromJson(decryptStr, GreetBean.class);
                            if (bean != null && bean.getData() != null && bean.getData().getCallContents() != null) {
                                OneTouchChatDialog.Companion.getData().clear();
                                OneTouchChatDialog.Companion.getData().addAll(bean.getData().getCallContents());
                            }
                        } catch (JsonSyntaxException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getHelpInformation() {
        NetUtils.getInstance().getApiService().getHelpInformation()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<com.luoxiang.lib_common.bean.NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(com.luoxiang.lib_common.bean.NumberBean value) {
                        String data = value.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        HelpInformation helpInformation = gson.fromJson(decryptStr, HelpInformation.class);

                        if (helpInformation == null || helpInformation.getData() == null) return;
                        MmkvUtil.INSTANCE.encode(HELP_INFORMATION, helpInformation.getData().getContactInformation());
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }


    /**
     * 获取礼物列表
     */
    private void getGift(String token) {
        NetUtils.getInstance().getApiService().getGifts(token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<com.luoxiang.lib_common.bean.NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(com.luoxiang.lib_common.bean.NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Gson gson = new Gson();
                        com.netease.yunxin.kit.chatkit.ui.model.GiftBean giftBean = gson.fromJson(decryptStr, com.netease.yunxin.kit.chatkit.ui.model.GiftBean.class);
                        if (giftBean != null) {
                            if (giftBean.getCode() == 0 && giftBean.getData() != null) {
                                MmkvUtil.INSTANCE.encode("GIFT_DATA", giftBean.getData());
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void initUIConfig() {
        ConversationUIConfig config = new ConversationUIConfig();
        config.showTitleBarLeftIcon = false;
        config.titleBarTitle = getString(R.string.mi_xiaoxi);
        config.showTitleBarRight2Icon = false;
        config.titleBarRightRes = R.mipmap.icon_sandian;

        ic_right = findViewById(config.titleBarRightRes);

        //1、实现点击事件
        config.itemClickListener = new ItemClickListener() {
            @Override
            public boolean onClick(Context context, ConversationBean data, int position) {
                //可以参考默认实现，默认实现是跳转到聊天页面
                XKitRouter.withKey(data.router).withParam(data.paramKey, data.param).withContext(context).navigate();
                return false;
            }

            @Override
            public boolean onLongClick(Context context, ConversationBean data, int position) {
                return false;
            }
        };
        ConversationKitClient.setConversationUIConfig(config);
        ChatUIConfig configchat = new ChatUIConfig();
        MessageProperties properties = new MessageProperties();
        configchat.messageProperties = properties;
        properties.receiveMessageRes = R.drawable.shape_bkgreen;
        properties.selfMessageRes = R.drawable.shape_minemesage;
        properties.setShowP2pMessageStatus(false);
        ChatKitClient.setChatUIConfig(configchat);
    }

    private void initViewByRG() {
        mFragments = new ArrayList<>();
        mFragments.add(new HomeFragment());
        mFragments.add(new CommunityFragment());
        mFragments.add(new ListFragment());
        mFragments.add(new ConversationFragment());
        mFragments.add(new MineFragment());

        // init view pager
        vpMain.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(),getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getItemCount() {
                return mFragments.size();
            }
        });
        // register listener
        vpMain.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position != 0) {
                    RadioButton first = (RadioButton) rgMain.getChildAt(0);
                    first.setChecked(false);
                }
                RadioButton radioButton = (RadioButton) rgMain.getChildAt(position);
                radioButton.setChecked(true);
                isShowGift = position != 2;
            }
        });
        vpMain.setUserInputEnabled(false);
        rgMain.setOnCheckedChangeListener(mOnCheckedChangeListener);
    }

    private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (position != 0) {
                RadioButton first = (RadioButton) rgMain.getChildAt(0);
                first.setChecked(false);
            }
            RadioButton radioButton = (RadioButton) rgMain.getChildAt(position);
            radioButton.setChecked(true);
            isShowGift = position != 2;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            for (int i = 0; i < group.getChildCount(); i++) {
                if (group.getChildAt(i).getId() == checkedId) {
                    vpMain.setCurrentItem(i);
                    return;
                }
            }
        }
    };

    private void getHomeUserInfo(String token, String extra) {
        NetUtils2.getInstance().getApiService().getHomeUserInfo(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            LogUtils.i("decryptStr0", decryptStr);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {

                            Gson gson = new Gson();
                            MineInfoBean bean = gson.fromJson(decryptStr, MineInfoBean.class);
                            if (bean != null) {
                                if (bean.getData() != null) {
                                    if (bean.getData().getUser() != null) {
                                        MmkvUtil.INSTANCE.encode("usericon", bean.getData().getUser().getIcon());
                                    }
                                }
                            }
                        } catch (Exception e) {
                            LogUtils.e("decryptStr0", e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.i("xx", e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 网易云信IM
     *
     * @param account
     * @param token
     */
    public void doLogin(String account, String token) {
        LoginInfo loginInfo = LoginInfo.LoginInfoBuilder.loginInfoDefault(account, token).build();
        IMKitClient.loginIM(loginInfo, new LoginCallback<LoginInfo>() {
            @Override
            public void onError(int errorCode, @NonNull String errorMsg) {
                //登录失败
                ToastUtils.showShort("云信登陆失败");
                LogUtils.i("XINXI", "登陆失败" + errorCode);
            }

            @Override
            public void onSuccess(@Nullable LoginInfo data) {
                //登录成功
                LogUtils.i("XINXI", "登陆成功");
                NERtcOption neRtcOption = new NERtcOption();
                neRtcOption.logLevel = NERtcConstants.LogLevel.DEBUG;
                neRtcOption.logDir = getCacheDir().getAbsolutePath();
                //正式f3cfe81e713709e6e61eb9a5dc65b51d
                CallKitUIOptions options = new CallKitUIOptions.Builder()
                        .rtcSdkOption(neRtcOption)
                        .rtcAppKey("f31308a092ca2a9afaa474af066c1935")
                        .p2pAudioActivity(TestActivity.class)
                        .p2pVideoActivity(TestActivity.class)
                        .currentUserAccId(com.luoxiang.lib_common.utils.MmkvUtil.INSTANCE.decodeInt(ACCID) + "")
                        // 通话接听成功的超时时间单位 毫秒，默认30s
                        .timeOutMillisecond(30 * 1000L)
                        // 此处为 收到来电时展示的 notification 相关配置，如图标，提示语等。
                        .notificationConfigFetcher(invitedInfo -> new CallKitNotificationConfig(R.mipmap.lovatrue))
                        // 收到被叫时若 app 在后台，在恢复到前台时是否自动唤起被叫页面，默认为 true
                        .resumeBGInvitation(true)
                        // 呼叫组件初始化 rtc 范围，true-全局初始化，false-每次通话进行初始化以及销毁
                        // 全局初始化有助于更快进入首帧页面，当结合其他组件使用时存在rtc初始化冲突可设置false
                        .rtcCallExtension(new SelfNERtcCallExtension())
                        .rtcInitScope(false)
                        .currentUserRtcUId(com.luoxiang.lib_common.utils.MmkvUtil.INSTANCE.decodeInt(ACCID))
                        .build();

                CallKitUI.init(getApplicationContext(), options);
                MyAppliaction.initUMSystemMassage();
                MyAppliaction.getMyAppliaction().startWhetherReceivePopovers();
                LiveEventBus.get("iMLoginSuccess").post(null);
                NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                        new Observer<StatusCode>() {
                            public void onEvent(StatusCode status) {
                                //获取状态的描述
                                String desc = status.getDesc();
                                if (status == StatusCode.KICKOUT) {
                                    MmkvUtil.INSTANCE.encode(TOKEN, "");
                                    MmkvUtil.INSTANCE.encode(ACCID, "");
                                    MmkvUtil.INSTANCE.encode(IMTOKEN, "");
                                    MmkvUtil.INSTANCE.encode(HOSTAUDIT, "");
                                    MmkvUtil.INSTANCE.encode(USER_NAME, "");
                                    MmkvUtil.INSTANCE.encode("phone", "");
                                    MmkvUtil.INSTANCE.encode(USERID, "");
                                    MmkvUtil.INSTANCE.encode("datingModeId", "");
                                    MmkvUtil.INSTANCE.encode("emotioRelationId", "");
                                    MmkvUtil.INSTANCE.encode("targetAgeId", "");
                                    MmkvUtil.INSTANCE.encode("sexpait", "");
                                    MmkvUtil.INSTANCE.encode("ed_rename", "");
                                    MmkvUtil.INSTANCE.encode("isshowdialogbatch", "");
                                    MmkvUtil.INSTANCE.encode("usericon", "");
                                    LoginUtil.Companion.initLogin(
                                            HomeActivity.this,
                                            result -> {
                                                LoginUtil.Companion.startLogin(HomeActivity.this, result);
                                                ToastUtils.showShort(getString(R.string.mi_dangqianzhanghaoyibeidenglu));
                                                finish();
                                                return null;
                                            },
                                            () -> {
                                                return null;
                                            },
                                            () -> {
                                                clearLoading();
                                                return null;
                                            });
                                }
                            }
                        }, true);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AllenVersionChecker.getInstance().cancelAllMission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getNewversion(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA, "0");
    }
}